/*
 * bcd.hpp
 *
 *  Created on: 2019-4-13
 *      Author: work
 */

#ifndef _DM_BCD_HPP_
#define _DM_BCD_HPP_

#include <dm/types.hpp>

namespace dm{

inline dm::uint8 fromBcd1( const dm::uint8& bcd ){
	return bcd&0x0F;
}

inline dm::uint8 toBcd1( const dm::uint8& v ){
	return v%10;
}

inline dm::uint8 fromBcd2( const dm::uint8& bcd ){
	return fromBcd1(bcd)+fromBcd1(bcd>>4)*10;
}

inline dm::uint8 toBcd2( const dm::uint8& v ){
	return toBcd1(v)|(toBcd1((v%100)/10)<<4);
}

inline dm::uint16 fromBcd4( const dm::uint16& bcd ){
	return fromBcd2(bcd)+fromBcd2(bcd>>8)*dm::uint16(100);
}

inline dm::uint16 toBcd4( const dm::uint16& v ){
	return toBcd2(v)|((dm::uint16)toBcd2(v/100)<<8);
}

inline dm::uint32 fromBcd8( const dm::uint32& bcd ){
	return fromBcd4(bcd)+fromBcd4(bcd>>16)*dm::uint32(10000);
}

inline dm::uint32 toBcd8( const dm::uint32& v ){
	return toBcd4(v)|((dm::uint32)toBcd4(v/10000)<<16);
}

inline dm::uint64 fromBcd16( const dm::uint64& bcd ){
	return fromBcd8(bcd)+fromBcd8(bcd>>32)*dm::uint64(100000000);
}

inline dm::uint64 toBcd16( const dm::uint64& v ){
	return toBcd8(v)|((dm::uint64)toBcd8(v/100000000)<<32);
}

}

#endif /* DM_RUNTIME_INCLUDE_DM_BCD_HPP_ */
